// pages/water/water.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 喝水相关数据
    targetWaterAmount: 2000, // 默认目标喝水量(ml)
    currentWaterAmount: 0,   // 当前喝水量(ml)
    waterPercentage: 0,      // 完成百分比
    
    // 植物生长状态 (0-4: 枯萎->复苏->生长->茂盛->开花)
    plantGrowthStage: 0,
    
    // 植物是否已种在花园
    isPlanted: false,
    
    // 植物生长阶段名称
    plantStageNames: ['枯萎', '复苏', '生长', '茂盛', '开花'],
    
    // 记录日期，用于每日重置
    lastRecordDate: '',
    
    // 输入新喝水量的临时变量
    newWaterAmount: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadUserData();
    this.checkDateAndReset();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.checkDateAndReset();
    this.updatePlantGrowth();
  },

  /**
   * 加载用户数据
   */
  loadUserData() {
    const data = wx.getStorageSync('waterTrackerData');
    if (data) {
      this.setData({
        targetWaterAmount: data.targetWaterAmount || 2000,
        currentWaterAmount: data.currentWaterAmount || 0,
        plantGrowthStage: data.plantGrowthStage || 0,
        isPlanted: data.isPlanted || false,
        lastRecordDate: data.lastRecordDate || ''
      });
      this.calculatePercentage();
    }
  },

  /**
   * 保存用户数据
   */
  saveUserData() {
    const data = {
      targetWaterAmount: this.data.targetWaterAmount,
      currentWaterAmount: this.data.currentWaterAmount,
      plantGrowthStage: this.data.plantGrowthStage,
      isPlanted: this.data.isPlanted,
      lastRecordDate: this.data.lastRecordDate
    };
    wx.setStorageSync('waterTrackerData', data);
  },

  /**
   * 检查日期并重置（每日重置喝水量）
   */
  checkDateAndReset() {
    const today = new Date().toDateString();
    if (this.data.lastRecordDate !== today && !this.data.isPlanted) {
      this.setData({
        currentWaterAmount: 0,
        plantGrowthStage: 0,
        lastRecordDate: today
      });
      this.calculatePercentage();
      this.saveUserData();
    }
  },

  /**
   * 计算完成百分比
   */
  calculatePercentage() {
    const percentage = Math.min(100, Math.round((this.data.currentWaterAmount / this.data.targetWaterAmount) * 100));
    this.setData({ waterPercentage: percentage });
  },

  /**
   * 更新植物生长状态
   */
  updatePlantGrowth() {
    const percentage = this.data.waterPercentage;
    let stage = 0;
    
    if (percentage >= 100) {
      stage = 4; // 开花
    } else if (percentage >= 75) {
      stage = 3; // 茂盛
    } else if (percentage >= 50) {
      stage = 2; // 生长
    } else if (percentage >= 25) {
      stage = 1; // 复苏
    }
    
    this.setData({ plantGrowthStage: stage });
  },

  /**
   * 设置目标喝水量
   */
  setTargetAmount(e) {
    const amount = parseInt(e.detail.value);
    if (!isNaN(amount) && amount > 0) {
      this.setData({ targetWaterAmount: amount });
      this.calculatePercentage();
      this.updatePlantGrowth();
      this.saveUserData();
      this.showToast('目标设置成功', 'success');
    } else {
      this.showToast('请输入有效数字', 'error');
    }
  },

  /**
   * 输入喝水量
   */
  inputWaterAmount(e) {
    this.setData({ newWaterAmount: e.detail.value });
  },

  /**
   * 添加喝水量
   */
  addWaterAmount() {
    const amount = parseInt(this.data.newWaterAmount);
    if (!isNaN(amount) && amount > 0) {
      const newAmount = this.data.currentWaterAmount + amount;
      this.setData({ 
        currentWaterAmount: newAmount,
        newWaterAmount: ''
      });
      this.calculatePercentage();
      this.updatePlantGrowth();
      this.saveUserData();
      
      // 动态生长动画效果
      this.animatePlantGrowth();
      
      // 添加水滴动画效果
      const that = this;
      setTimeout(() => {
        that.showToast(`已添加${amount}ml`, 'success');
      }, 300);
    } else {
      this.showToast('请输入有效数字', 'error');
    }
  },

  /**
   * 植物生长动画效果
   */
  animatePlantGrowth() {
    const plantElement = wx.createSelectorQuery().select('#plant-container');
    plantElement.boundingClientRect(rect => {
      if (rect) {
        // 可以在这里添加简单的动画效果
        plantElement.animate(['opacity: 0.7', 'opacity: 1'], 500);
      }
    }).exec();
  },

  /**
   * 显示提示信息 - 支持不同类型
   */
  showToast(text, type = 'default') {
    let toastClass = '';
    
    // 根据类型设置不同的样式类
    switch (type) {
      case 'success':
        toastClass = 'toast-success';
        break;
      case 'warning':
        toastClass = 'toast-warning';
        break;
      case 'error':
        toastClass = 'toast-error';
        break;
      default:
        toastClass = '';
    }
    
    this.setData({
      showToast: true,
      toastText: text,
      toastClass: toastClass
    });
    
    setTimeout(() => {
      this.setData({
        showToast: false
      });
    }, 2000);
  },

  /**
   * 将植物种在花园
   */
  plantInGarden() {
    if (this.data.plantGrowthStage === 4) { // 只有开花状态才能种植
      this.setData({ isPlanted: true });
      this.saveUserData();
      
      // 保存到花园数据
      let gardenData = wx.getStorageSync('gardenPlants') || [];
      gardenData.push({
        id: Date.now(),
        name: '成长的植物',
        plantedDate: new Date().toDateString(),
        stage: 4
      });
      wx.setStorageSync('gardenPlants', gardenData);
      
      this.showToast('植物已种入花园！', 'success');
    } else {
      this.showToast('请先完成今日喝水目标', 'warning');
    }
  },

  /**
   * 重置今日数据
   */
  resetTodayData() {
    wx.showModal({
      title: '确认重置',
      content: '确定要重置今日喝水记录吗？这将清除所有记录并重新开始。',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            currentWaterAmount: 0,
            plantGrowthStage: 0,
            isPlanted: false
          });
          this.calculatePercentage();
          this.saveUserData();
          this.showToast('已重置', 'warning');
        }
      }
    });
  }
})